import { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import menuAPI, { MenuVO } from "@/api/menu";

const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  /** 所有路由，包括静态和动态路由 */
  const routes = ref<RouteRecordRaw[]>([]);
  /** 混合模式左侧菜单 */
  const mixLeftMenus = ref<RouteRecordRaw[]>([]);

  /**
   * 生成动态路由
   */
  function generateRoutes() {
    return new Promise<RouteRecordRaw[]>(async (resolve, reject) => {
      const userId = localStorage.getItem("userId");
      let routeList: any = [];
      if (userId) {
        await menuAPI
          .getMenuQueryById(Number(userId))
          .then((data: any) => {
            const matchingItem = findMatchingItem(constantRoutes, data);
            // console.log(
            //   constantRoutes,
            //   "全部路由",
            //   data,
            //   "请求的路由",
            //   matchingItem,
            //   "过滤的路由"
            // );

            routeList = matchingItem;
          })
          .catch((error) => {
            reject(error);
          });
      }
      if (routeList) {
        routes.value = routeList;
        resolve(routeList);
      } else {
        reject("无路由");
      }
    });
  }
  // 查找匹配项的函数
  function findMatchingItem(originalArray: any, requestedArray: any) {
    const matches = [];
    const pathMap = new Map(); // 使用 Map 来存储路径到对象的映射

    // 构建路径到对象的映射
    for (const item of originalArray) {
      pathMap.set(item.path, { ...item, children: [] }); // 初始化子级数组为空
      if (item.children) {
        for (const child of item.children) {
          pathMap.set(child.path, child); // 子级路径直接映射到子级对象
        }
      }
    }

    // 遍历请求数组，查找匹配项并构建结构
    for (const requestedItem of requestedArray) {
      const parentPath = requestedItem.menuUrl;
      const parent = pathMap.get(parentPath);
      if (parent) {
        // 创建父级对象的副本，并添加匹配的子级
        const matchingParent = { ...parent, children: [] };
        if (requestedItem.children && requestedItem.children.length > 0) {
          for (const requestedChild of requestedItem.children) {
            const childPath = requestedChild.menuUrl;
            const child = pathMap.get(childPath);
            if (child) {
              matchingParent.children.push(child); // 添加匹配的子级到父级
            }
          }
        }
        matches.push(matchingParent); // 添加构建好的父级对象到结果数组
      }
    }
    const newArray = originalArray.slice(0, 3);
    newArray.forEach((item: any) => {
      matches.unshift(item);
    });

    return matches;
  }

  /**
   * 混合模式菜单下根据顶部菜单路径设置左侧菜单
   *
   * @param topMenuPath - 顶部菜单路径
   */
  const setMixLeftMenus = (topMenuPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === topMenuPath);
    if (matchedItem && matchedItem.children) {
      mixLeftMenus.value = matchedItem.children;
    }
  };

  return {
    routes,
    generateRoutes,
    mixLeftMenus,
    setMixLeftMenus,
  };
});

/**
 * 转换路由数据为组件
 */
const transformRoutes = (routes: any) => {
  const asyncRoutes: RouteRecordRaw[] = [];
  routes.forEach((route: any) => {
    const tmpRoute = { ...route } as RouteRecordRaw;
    // 顶级目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == "Layout") {
      tmpRoute.component = Layout;
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`];
      if (component) {
        tmpRoute.component = component;
      } else {
        tmpRoute.component = modules[`../../views/error-page/404.vue`];
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = transformRoutes(route.children);
    }

    asyncRoutes.push(tmpRoute);
  });

  return asyncRoutes;
};

/**
 * 在组件外使用 Pinia store 实例
 * @see https://pinia.vuejs.org/core-concepts/outside-component-usage.html
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
